<template>
  <div style="display: inline-block;text-align: left;">
    <el-button type="primary" size="small" @click="openExcal">{{
      $t("staff.batch_import")
    }}</el-button>
    <el-dialog
      v-if="dialogTableVisible"
      :visible.sync="dialogTableVisible"
      :title="$t('staff.batch_import')"
      :before-close="closeDia"
      width="70%"
    >

      <upload-excel-component
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        :imgList="imgList"
        :formData="formData"
      />
      <el-table
        :data="data_list"
        border
        highlight-current-row
        style="width: 100%;margin-top:20px;"
      >
        <el-table-column
          v-for="item of header"
          :key="item"
          :prop="item"
          :label="item"
        />
      </el-table>
      <!-- 图片上传 -->
      <!-- <el-upload
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :http-request="uploadAvatar"
        :before-upload="beforeAvatarUpload"
        :file-list="fileList"
        action="#"
        webkitdirectory
        list-type="picture-card"
      >
        <i class="el-icon-plus"/>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img :src="dialogImageUrl" width="100%" alt="">
      </el-dialog> -->
      <div class="top">
        {{ this.$t("staff.import_tip1") }}
      </div>
      <input
        id="uploadFile"
        type="file"
        webkitdirectory
        @change="handleChange"
      >
      <el-button
        type="primary"
        size="small"
        class="imgto"
      >{{$t('staff.upload_file')}}</el-button
      >
      <span>{{$t('staff.upload_file_num')}}：{{ imgList.length }}</span>

      <el-form align="right" class="dialog-footer">
        <el-button @click="Cancel">{{
          $t("table.cancel")
        }}</el-button>
        <el-button type="primary" @click="open">{{
          $t("table.complete")
        }}</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import store from '@/store'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { service_batchLoad } from '@/api/user_manage/user_manage'
import { push_get_list } from '@/api/user_manage/user_manage'
export default {
  components: {
    UploadExcelComponent
  },
  data() {
    return {
      file: null,
      dialogImageUrl: '',
      dialogVisible: false,
      picList: [],
      fileList: [],
      base64: null,
      base64type: null,
      imgList: [],
      dialogTableVisible: false,
      data_list: [],
      data_header: null,
      fileName: null,
      formData: [],
      header: {},
      Equipment: {},
      date_time: null
    }
  },
  created() {
    this.time()
  },
  methods: {
    time() {
      // 当前时间
      const date = new Date() // 时间戳为10位需乘1000，为13位则不用
      const Y = date.getFullYear() // 年
      const M =
        date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1 // 月

      const D =
        date.getDate() < 10 ? '0' + date.getDate() + '' : date.getDate()
      const hour = date.getHours()
      // var minu = date.getMinutes()
      var mm = date.getMinutes()
      if (mm < 10) mm = '0' + mm
      var sec = date.getSeconds()
      this.date_time =
        Y + '-' + M + '-' + D + ' ' + hour + ':' + mm + ':' + sec
      console.log(date_time, 'data——time')
    },
    // closeDialog(type){
    //   console.log(type,'type')
    //   if(type){
    //     this.$refs[type].reseFields();
    //   }
    // },
    openExcal() {
      this.data_list = null
      this.dialogTableVisible = true
      // 获取门禁数据
      push_get_list(store.getters.token).then(res => {
        this.Equipment = res.data.list.data
      })
    },
    handleSuccess({ results, header }) {
      const that = this
      this.data_list = results
      let i = 0
      for (const item in this.data_list[0]) {
        if (i == 0) this.header.person_id = item
        if (i == 1) this.header.name = item
        if (i == 2) this.header.company = item
        if (i == 3) this.header.department = item
        if (i == 4) this.header.employee_card_id = item
        // if (i == 5) this.header.person_ts = item.
        // if (i == 5) this.header.role_name = item
        // if (i == 6) this.header.schedule_id = item
        // if (i == 7) this.header.gender = item
        if (i == 8) this.header.image_type = item
        // if (i == 10) this.header.deviceAuth = item
        // if (i == 11) this.header.deviceAuth.sn = item
        // if (i == 12) this.header.deviceAuth.conunt = item
        i++
      }
      results.forEach(item => {
        const data = {
          person_id: item[header[0]],
          name: item[header[1]],
          company: item[header[2]],
          department: item[header[3]],
          employee_card_id: item[header[4]],
          // person_ts: item[header[5]],
          role_name: item[header[5]],
          schedule_id: item[header[6]],
          gender: item[header[7]],
          image_type: item[header[8]]
          // deviceAuth: item[header[10]]
          // sn : item[header[10][0]],
          // conunt : item[header[10][1]]
        }
        this.formData.push(data)
      })

      // this.Equipment.forEach(item => {
      //   console.log(item, 'item11111111')
      //   const listSn = {
      //     sn: item.sn,
      //     conunt: '-1'
      //   }
      //   for (const i in this.formData) {
      //     if (item.name == this.formData[i].sn) {
      //       // console.log(this.formData.deviceAuth[i]['sn'],'.formData.deviceAuth')
      //       this.formData[i].deviceAuth = [this.formData[i]['sn'] = item.sn, this.formData[i]['conunt'] = '-1']
      //     } else if (item.name == '所有设备') {
      //       this.formData[i].deviceAuth = [this.formData[i]['sn'] = '*', this.formData[i]['conunt'] = '-1']
      //     }
      //   }
      // })
      console.log(this.formData, 'fffffffffffffffffffff')

      console.log(header, 'header')
    },
    beforeUpload(file) {
      console.log(file, 'file')
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: this.$t('staff.import_tip3'),
        type: 'warning'
      })
      return false
    },
    // 传入person_id获取对应图片的base64
    getImgId(person_id) {
      if (this.imgList.filter(item => item.person_id == person_id)[0]) {
        var data = {
          base64: this.imgList.filter(item => item.person_id == person_id)[0]
            .base64,
          base64type: this.imgList.filter(
            item => item.person_id == person_id
          )[0].base64type
        }
        return data
      } else {
        return { base64: null, base64type: null }
      }
    },
    open() {
      console.log(this.imgList, 'aaaaaaaaaaaaaaaaa')
      this.formData.forEach(item => {
        console.log(item, 'item')
        item['face_pic'] = this.getImgId(item.person_id).base64
        item['image_type'] = this.getImgId(item.person_id).base64type
        item['person_ts'] = this.date_time
        item['image_enc'] = false
        // item["sn"] = this.formData.sn
        // item["conunt"] =this.data_list.conunt
      })
      service_batchLoad(store.getters.token, { person: this.formData }).then(
        res => {
          console.log(res, 'resssss')
          if (res.data.status) {
            this.$message.success(this.$t('table.add_complete'))
            this.$emit('getLists')
            this.dialogTableVisible = false
          } else {
            this.$message.error(this.$t('table.add_fail' + ':' + res.data.msg))
          }
        }
      )
    },
    //取消按钮
    Cancel(){
      this.formData = []
      this.imgList = []
      this.dialogTableVisible = false
    },
    closeDia() {
      this.formData = []
      this.imgList = []
      this.dialogTableVisible = false
    },

    // 上传图片
    handleChange() {
      const files = document.getElementById('uploadFile').files // FileList 伪数组对象
      for (let i = 0; i <= files.length - 1; i++) {
        const file = files[i] // File 对象
        if (
          file.type == 'image/png' ||
          file.type === 'image/jpeg' ||
          file.type === 'image/jpg'
        ) {
          const reader = new FileReader()
          reader.readAsDataURL(file)
          const that = this
          // 创建一个img对象
          const img = new Image()
          reader.onload = e => {
            img.src = e.target.result
            // base64地址图片加载完毕后执行
            img.onload = function() {
              // 缩放图片需要的canvas（也可以在DOM中直接定义canvas标签，这样就能把压缩完的图片不转base64也能直接显示出来）
              var canvas = document.createElement('canvas')
              var context = canvas.getContext('2d')
              // 图片原始尺寸
              var originWidth = this.width
              var originHeight = this.height
              // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
              var maxWidth = 750,
                maxHeight = 750
              if (originWidth< 750 || originHeight < 750) {
                that.$message.error(that.$t("validation.img_tip3"));
              }
              // 目标尺寸
              var targetWidth = originWidth,
                targetHeight = originHeight
              // 图片尺寸超过最大尺寸的限制
              if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 更改宽度，按照宽度限定尺寸
                  targetWidth = maxWidth
                  targetHeight = Math.round(
                    maxWidth * (originHeight / originWidth)
                  )
                } else {
                  targetHeight = maxHeight
                  targetWidth = Math.round(
                    maxHeight * (originWidth / originHeight)
                  )
                }
              }
              // 对图片进行缩放
              canvas.width = targetWidth
              canvas.height = targetHeight
              // 清除画布
              context.clearRect(0, 0, targetWidth, targetHeight)
              // 图片压缩
              context.drawImage(img, 0, 0, targetWidth, targetHeight)
              /* 第一个参数是创建的img对象；第二三个参数是左上角坐标，后面两个是画布区域宽高*/
              // 压缩后的base64文件
              var newUrl = canvas.toDataURL('image/jpeg', 0.92)
              console.log(newUrl, '1111111111111111222222222')
              // that.base64 = newUrl.split(",")[1];
              // that.base64type = newUrl.split(",")[0];

              const base64 = newUrl.split(',')[1]
              const base64type = newUrl.split(',')[0]
              const data = {
                person_id: file.name.toString().split('.')[0],
                base64: base64,
                base64type: base64type
              }
              that.imgList.push(data)
              console.log(data, 'data')
              console.log(that.imgList, 'this,imglist')
            }
          }
        }
      }
      this.imgList = JSON.parse(JSON.stringify(this.imgList))
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  margin-top: 20px;
}
.top {
  margin-top: 20px;
  margin-bottom: 20px;
  font-size: 16px;
}
#uploadFile {
  opacity: 0;
}
.imgto {
  margin-left: -280px;
}
</style>
